#!/usr/bin/env python

import gdata.docs.data, gdata.docs.client
import yaml, sys, mimetypes, os
from getpass import getpass
from optparse import OptionParser

client = gdata.docs.client.DocsClient()
client.ssl = True
client.http_client.debug = False


parser = OptionParser()
parser.add_option("-u", "--upload", dest="files",
                  help="Upload files to google docs.  May be comma seperated", metavar="FILES", default=[])
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")
parser.add_option("-c", "--config",
                  dest="config", default="%s/.gdocs_cli.yaml" % os.getenv("HOME"),
                  help="explicitly define the path to the config file")

def upload(filelist):
    for file in filelist:
        print "Uploading file: %s" % file
        mime = mimetypes.guess_type(file)[0]
        ms = gdata.data.MediaSource(file_path=file, content_type=mime)
        entry = client.Upload(ms, os.path.basename(file))
    print "Finished uploading %d files." % len(filelist)

if __name__ == "__main__":
    (options, args) = parser.parse_args()
    #pull in our login information from our yaml config
    try:
        print options.config
        configs = yaml.load(open(options.config).read())
    except IOError:
        print ".gdocs_cli.yaml not found.  Have you edited example.yaml and put it in ~/.gdco_cli.yaml?\n"
        configs={}
        configs["email"] = raw_input("Email Address:")
        configs["password"] = getpass("Password:")
    
    #Try to log in to google docs
    try:
        client.ClientLogin(configs["email"], configs["password"], client.source);
    except gdata.client.BadAuthentication:
        print "Incorrect username or password"
        sys.exit(1)


    if  options.files:
        upload(options.files.split(","))
    else:
        parser.print_help()
        sys.exit(1)

